const choices = document.querySelectorAll('.choice')
const score = document.getElementById('score')
const result = document.getElementById('result')
const restart = document.getElementById('restart')
const modal = document.querySelector('.modal')
// 计分板
const scoreBoard = {
    player: 0,
    computer: 0
}

// 封装函数,点击时触发
function play(e) {
    // 显示按钮
    restart.style.display = 'inline-block'
    // 获取玩家的选择
    const playerChoice = e.target.id
    // 获得电脑的选择
    const computerChoice = getComputerChoice()

    // 决定胜负
    const winner = getWinner(playerChoice,computerChoice)

    // 显示胜负
    showWinner(winner,computerChoice)
}

// 封装获得电脑选择的函数
function getComputerChoice() {
    const rand = Math.random()
    if(rand < 0.33) {
        return 'rock'
    } else if(rand <= 0.67) {
        return 'paper'
    } else {
        return 'scissors'
    }
}

// 得到胜者的函数
function getWinner(p,c) {
    if(p === c) {
        return 'draw'
    } else if (p === 'rock') {
        if(c === 'paper') {
            return 'computer'
        } else {
            return 'player'
        }
    } else if (p === 'paper') {
        if(c === 'scissors') {
            return 'computer'
        } else {
            return 'player'
        }
    } else if (p === 'scissors') {
        if(c === 'rock') {
            return 'computer'
        } else {
            return 'player'
        }
    }
}

// 显示胜负的函数
function showWinner(winner,computerChoice) {
    if(winner === 'player') {
        scoreBoard.player++;
        result.innerHTML = `
        <h1 class="text-win">恭喜你,你赢了!</h1>
        <p>电脑的选择为</p>
        <i class="fa fa-hand-${computerChoice} fa-10x"></i>
        `
    } else if(winner === 'computer') {
        scoreBoard.computer++;
        result.innerHTML = `
        <h1 class="text-lose">抱歉,你输了</h1>
        <p>电脑的选择为</p>
        <i class="fa fa-hand-${computerChoice} fa-10x"></i>
        `
    } else {
        result.innerHTML = `
        <h1>平局</h1>
        <p>电脑的选择为</p>
        <i class="fa fa-hand-${computerChoice} fa-10x"></i>
        `
    }

    // 显示分数
    score.innerHTML = `
    <p>玩家:${scoreBoard.player}</p>
    <p>电脑:${scoreBoard.computer}</p>
    `

    // 显示模态框
    modal.style.display = 'block'
}

// 监听事件
choices.forEach(choice => choice.addEventListener('click', play))

// 关闭弹出层
window.addEventListener('click',function(e) {
    if(e.target == modal) {
        modal.style.display = 'none'
    }
})

// 按钮点击事件
restart.addEventListener('click',function(e) {
    scoreBoard.player = 0
    scoreBoard.computer = 0
    score.innerHTML = `
    <p>玩家:0</p>
    <p>电脑:0</p>
    `
    this.style.display = 'none'
})